package com.wf.course.web.controller.goods;

 import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mysql.jdbc.StringUtils;
import com.utils.dateUtil.DateUtil;
import com.utils.page.PageBean;
import com.wf.course.model.ad.VipCard;
import com.wf.course.model.course.CourseChapter;
import com.wf.course.model.course.CourseInfo;
import com.wf.course.model.goods.GoodsInfo;
import com.wf.course.model.goods.GoodsOrder;
import com.wf.course.model.goods.GoodsOrderRelation;
import com.wf.course.model.member.CoinLog;
import com.wf.course.service.ICoinLogService;
import com.wf.course.service.ICourseChapterService;
import com.wf.course.service.ICourseInfoService;
import com.wf.course.service.IGoodsInfoService;
import com.wf.course.service.IGoodsOrderRelationService;
import com.wf.course.service.IGoodsOrderService;
import com.wf.course.service.IVipCardService;
import com.wf.course.web.Interceptor.LogInfo;
/**
 * 
 * @content 列表Controller
 */
@RequestMapping("goodsOrderRelation")
@Controller
public class GoodsOrderRelationController {

	@Autowired
	private IGoodsOrderService goodsOrderService;
	@Autowired
	private IGoodsOrderRelationService orlService;
	@Autowired
	private ICourseInfoService courseInfoService;
	@Autowired
	private ICourseChapterService chapterService;
	@Autowired
	private IVipCardService cardService;
	@Autowired
	private IGoodsInfoService goodsInfoService;
	@Autowired
	private ICoinLogService coinLogService;

	/**
	 * 列表展示
	 * @param pageNo
	 * @param pageSize
	 * @param orderCode
	 * @param model
	 * @return
	 */
	@RequestMapping("goodsOrderRelationList")
	public String goodsOrderList(@RequestParam(value = "pageNo", required = false) Integer pageNo,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			@RequestParam(value = "orderCode", required = false) String orderCode, 
			@RequestParam(value = "orderStatus", required = false) String orderStatus, 
			@RequestParam(value = "telephone", required = false) String telephone, 
			@RequestParam(value = "backFlag", required = false) String backFlag, 
			Model model) {

		// 组装一个查询条件的map
		Map<String, Object> cons = new HashMap<String, Object>();
		if(orderCode!=null && orderCode!=""){
			cons.put("orderCode", orderCode);
		}
		if(orderStatus!=null && orderStatus!=""){
			cons.put("orderStatus", orderStatus);
		}
		if(telephone!=null && telephone!=""){
			cons.put("telephone", telephone);
		}
		if(backFlag!=null && backFlag!=""){
			cons.put("backFlag", backFlag);
		}
		 
		PageBean<GoodsOrderRelation> pageBean = new PageBean<GoodsOrderRelation>(pageNo, pageSize, null, cons);
		
		pageBean.setUrl("goodsOrderRelation/goodsOrderRelationList");
		this.orlService.indexInfo(pageBean);
		
		model.addAttribute("page", pageBean);
		return "goods/goodsOrderRelationList";
	}

	/**
	 *  用户购买课程时，分为使用铜钱和未使用铜钱两种情况：
	 *  1.使用铜钱的订单：会产生两条铜钱记录，一条使用记录，一条赚取记录。	
	 *	如果要退货，会把那条使用铜钱的记录删除掉，相当于，购买时没有使用铜钱。
	 *	同时会把赚取的铜钱，也删掉，相当于在购买课程时，没有赚取铜钱	
	 *	2.未使用铜钱的订单：会产生一条铜钱记录，赚取记录。
	 *	如果要退货，会把赚取记录删掉。
	 *	以上两种在删除赚取记录时，删除的是整个订单的所赚取的铜钱，而不是按照部分删除的。
	 *	注：这里说的删除，都是逻辑删除（只修改删除状态，并非彻底删除数据）
	 *
	 * 删除订单下的商品,并修改订单总额,(只针对课程退货)
	 * @param id
	 * @return
	 */
	@ResponseBody
	@LogInfo("删除订单下某一商品，修改订单总额")
	@RequestMapping(value = "remove",method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	public String removeGoodsOrderRelation(@RequestParam("id") Integer id) {
		 
		GoodsOrderRelation gor  = orlService.queryGoodsOrderRelationById(id);
		//获取商品价格
		BigDecimal goodPrice = gor.getGoodsPrice();
		
		if(gor!=null){
			//根据订单编号查找铜钱
			GoodsOrder goder = goodsOrderService.queryGoodsOrderByOrderCode(gor.getOrderCode());
			//查询该订单所花的铜钱
			CoinLog coin = coinLogService.queryCoinLogByOrderCode(gor.getOrderCode(), 2);
			String coinValue ="0";
			if(coin!=null){
				coinValue = coin.getCoinValue();
				StringBuffer crk = new StringBuffer();
				if(coin.getRemarkInfo()!=null && !"".equals(coin.getRemarkInfo())){
					crk.append(coin.getRemarkInfo());
				}
				crk.append("【订单退货，返还用户购买时支付的铜钱，删除花费记录】");
				
				//coin.setRemarkInfo(crk.toString());
				//coin.setDeleteFlag(1);
				//更新删除标识和备注
				//coinLogService.saveOrUpdateCoinLog(coin);
				coinLogService.updateCoinRemakById(crk.toString(), 1, coin.getId());
			}
			//铜钱值
			BigDecimal big1 = new BigDecimal(coinValue);
			
			if(goder!=null){
				//获取订单总额
				String orderAmount = goder.getOrderAmount();
				//获取商品总额
				String goodsAmount = goder.getGoodsAmount();
				BigDecimal big2 = new BigDecimal(orderAmount);
				BigDecimal big3 = new BigDecimal(goodsAmount);
				
				if(goodPrice==null){
					goodPrice=new BigDecimal(0.0);
				}
				//订单总额-商品价格
				big2=big2.subtract(goodPrice);
				//订单总额+使用的铜钱
				big2 = big2.add(big1);
				
				//商品总额-商品价格
				big3 = big3.subtract(goodPrice);
				//商品总额+使用的铜钱
				big3 = big3.add(big1);
				
				goder.setGoodsAmount(big3.toString());
				goder.setOrderAmount(big2.toString());
				goder.setCopperCash(null);
				StringBuffer rk = new StringBuffer();
				//备注是否为空
				if(goder.getOrderRemark()!=null && !"".equals(goder.getOrderRemark())){
					rk.append(goder.getOrderRemark());
				}
				rk.append("【本订单有退货】,退货商品为"+gor.getGoodsName());
				
				goder.setOrderRemark(rk.toString());
				
				goodsOrderService.saveGoodsOrderOrUpdate(goder);
			}
			
			
		}
		/**
		 * 1.根据商品类型判断，商品销量-1
		 * 2.课程 2.章节3.vip卡4商品
		 */

		if(!"".equals(gor.getGoodsSort()) && gor.getGoodsSort() ==1){
		 CourseInfo courseInfo = courseInfoService.queryCourseInfoById(gor.getGoodsId());
			if(courseInfo!=null && courseInfo.getCourseSaleNumber()!=0){
				courseInfo.setCourseSaleNumber(courseInfo.getCourseSaleNumber()-1);
				courseInfoService.updateCourseSaleNum(courseInfo);
			}
		}else if(!"".equals(gor.getGoodsSort()) && gor.getGoodsSort() ==2){
			CourseChapter chapter = chapterService.queryCourseChapterById(gor.getGoodsId());
			if(chapter!=null && chapter.getChapterSaleNumber()!=0){
				chapter.setChapterSaleNumber(chapter.getChapterSaleNumber()-1);
				chapterService.updateChapterSaleNum(chapter);
			}
		}else if(!"".equals(gor.getGoodsSort()) && gor.getGoodsSort() ==3){
			VipCard card = cardService.queryVipCardById(gor.getGoodsId());
			if(card!=null && card.getCardSaleNumber()!=0){
				card.setCardSaleNumber(card.getCardSaleNumber()-1);
				cardService.updateCardSaleNum(card);
			}
		}

//		更新退货标识
		orlService.updateBackFlag(id);
		//删除赚取铜钱记录
		CoinLog coinlg = coinLogService.queryCoinLogByOrderCode(gor.getOrderCode(), 1);
		if(coinlg!=null){
//			coinLogService.deleteById(coinlg.getId());
			StringBuffer crk = new StringBuffer();
			if(coinlg.getRemarkInfo()!=null && !"".equals(coinlg.getRemarkInfo())){
				crk.append(coinlg.getRemarkInfo());
			}
			
			
			//赚取的铜钱值
			BigDecimal	cv = new BigDecimal(coinlg.getCoinValue());
			//商品价格*0.1对应的铜钱数,保留两位小数
			BigDecimal gp = goodPrice.multiply(new BigDecimal(0.1).setScale(2, BigDecimal.ROUND_HALF_UP));
			//如果商品对应的铜钱数量，小于之前铜钱记录中赚取的铜钱，说明此订单可能有多个课程，
			//此时，只减去退货的课程对应的铜钱
			 if(gp.compareTo(cv)<0){
				
				 crk.append("【订单退货，扣除退货商品价格10%的铜钱】"+gp);
				 coinLogService.updateCoinValueById(cv.subtract(gp).toString(), crk.toString(),coinlg.getId());
			 }else{
				 //如果订单只有一个课程，修改删除标识
				 crk.append("【订单退货，扣除用户赚取的铜钱，删除赚取记录】");
				 coinLogService.updateCoinRemakById(crk.toString(), 1, coinlg.getId());
			 }
			}
 		
		return "1";
	}
	
	/**
	 *  修改和页面数据初始化
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("pageLoad/{id}")
	public String downLoadById(@PathVariable("id") Integer id, Model model) {
		 
		if (id != null && id != 0) {
			GoodsOrderRelation goodsOrderRelation = orlService.queryGoodsOrderRelationById(id);
			if(goodsOrderRelation.getGoodsSort()==1){
				goodsOrderRelation.setCourseId(goodsOrderRelation.getGoodsId());
			}else if(goodsOrderRelation.getGoodsSort()==2){
				goodsOrderRelation.setChapterId(goodsOrderRelation.getGoodsId());
			}else if(goodsOrderRelation.getGoodsSort()==3){
				goodsOrderRelation.setCardId(goodsOrderRelation.getGoodsId());
			}
			
			model.addAttribute("goodsOrderRelation", goodsOrderRelation);
			model.addAttribute("type", "upd");
		}else{
			model.addAttribute("type", "add");
		}
		 
		 List<CourseInfo> courses = courseInfoService.queryCourses();
		 model.addAttribute("courses",courses);
		 
		 List<CourseChapter> chapters = chapterService.queryCourseChapters();
		 model.addAttribute("chapters",chapters);
		 
		 List<VipCard> cards = cardService.queryVipCards();
		 model.addAttribute("cards",cards);
		 
		 List<GoodsInfo> goods = goodsInfoService.queryGoods();
		 model.addAttribute("goods",goods);
		 
		return "goods/goodsOrderRelationEdit";
	}
	
	
	/**
	 * 新增和修改
	 * @param goodsOrderRelation
	 * @return
	 */
	@LogInfo(" 新增或修改订单-商品关系信息")
	@RequestMapping(value = "goodsOrderRelationEdit" , produces = "text/html;charset=UTF-8")
	public String goodsParamEdit(@ModelAttribute GoodsOrderRelation goodsOrderRelation,HttpServletRequest request) {
		
		orlService.saveGoodsOrderRelationOrUpdate(goodsOrderRelation);
		
		return "redirect:/goodsOrderRelation/goodsOrderRelationList";
	}

	/**
	 * 商品销售统计
	 * @return
	 */
	@LogInfo("商品销售统计")
	@RequestMapping("goodsSalesStatistics")
	public String goodsSalesStatistics(Model model){
		String result = orlService.goodsSalesStatistics();
		model.addAttribute("echare",result);
		return "goods/goodsSalesStatistics";
	}
	
	/**
	 * 商品分类销售统计
	 * @param model
	 * @return
	 */
	@LogInfo("商品分类销售统计")
	@RequestMapping("goodsCategoriesSales")
	public String goodsCategoriesSales(@RequestParam(value="goodsSort",required=false) Integer goodsSort,
									   @RequestParam(value="courseId",required=false) Integer courseId,
									   @RequestParam(value="chapterId",required=false) Integer chapterId,
									   @RequestParam(value="cardId",required=false) Integer cardId,
									   @RequestParam(value="orderPayTime",required=false) String orderPayTime,
									   Model model){
		
		 List<CourseInfo> courses = courseInfoService.queryCourses();
		 model.addAttribute("courses",courses);
		 
		 List<CourseChapter> chapters = chapterService.queryCourseChapters();
		 model.addAttribute("chapters",chapters);
		 
		 List<VipCard> cards = cardService.queryVipCards();
		 model.addAttribute("cards",cards);
		 
		 Integer id = 1;
		 
		 if (goodsSort == null) {
			 goodsSort = 1;
		 }
		 
		 if(goodsSort == 1 && courseId !=null){
			 id = courseId;
		 }else if(goodsSort==2 && chapterId!=null){ 
			 id = chapterId;
		 }else if (goodsSort==3 && cardId != null) {
			 id=cardId;
		}else {
			id = 1;
		}
		if (StringUtils.isNullOrEmpty(orderPayTime)) {
			
			orderPayTime = DateUtil.getDateString(DateUtil.datetimeFormat);
		}
		 
		 //String result = orlService.goodsCategoriesSales(goodsSort, id);
		 String result = orlService.goodsCategoriesSalesByTimes(goodsSort,id,DateUtil.getStringtoString(orderPayTime,1));
		 model.addAttribute("result",result);
		 model.addAttribute("goodsSort",goodsSort);
		 model.addAttribute("courseId",courseId);
		 model.addAttribute("chapterId",chapterId);
		 model.addAttribute("cardId",cardId);
		 model.addAttribute("orderPayTime",orderPayTime);
		 
		 
		return "goods/goodsCategoriesSales";
	}
	
	/**
	 * 商品分类销售统计
	 * @param model
	 * @return
	 */
	@LogInfo("商品分类销售统计")
	@RequestMapping("goodsCategoriesSalesByDay")
	public String goodsCategoriesSalesByDay(@RequestParam(value="goodsSort",required=false) Integer goodsSort,
									   @RequestParam(value="courseId",required=false) Integer courseId,
									   @RequestParam(value="chapterId",required=false) Integer chapterId,
									   @RequestParam(value="cardId",required=false) Integer cardId,
									   @RequestParam(value="orderPayTime",required=false) String orderPayTime,
									   Model model){
		
		 List<CourseInfo> courses = courseInfoService.queryCourses();
		 model.addAttribute("courses",courses);
		 
		 List<CourseChapter> chapters = chapterService.queryCourseChapters();
		 model.addAttribute("chapters",chapters);
		 
		 List<VipCard> cards = cardService.queryVipCards();
		 model.addAttribute("cards",cards);
		 
		 Integer id = 1;
		 
		 if (goodsSort == null) {
			 goodsSort = 1;
		 }
		 
		 if(goodsSort == 1 && courseId !=null){
			 id = courseId;
		 }else if(goodsSort==2 && chapterId!=null){ 
			 id = chapterId;
		 }else if (goodsSort==3 && cardId != null) {
			 id=cardId;
		}else {
			id = 1;
		}
		if (StringUtils.isNullOrEmpty(orderPayTime)) {
			orderPayTime = DateUtil.getDateString(DateUtil.datetimeFormat);
		}
		 
		 //String result = orlService.goodsCategoriesSales(goodsSort, id);
		 String result = orlService.goodsCategoriesSalesByDay(goodsSort,id,orderPayTime);
		 model.addAttribute("result",result);
		 model.addAttribute("goodsSort",goodsSort);
		 model.addAttribute("courseId",courseId);
		 model.addAttribute("chapterId",chapterId);
		 model.addAttribute("cardId",cardId);
		 model.addAttribute("orderPayTime",orderPayTime);
		 
		 
		return "goods/goodsCategoriesSalesByDay";
	}
}

